<?php

namespace app\api\logic;

use app\api\cache\Marketing;
use app\api\cache\MemberCache;
use app\api\consDir\ErrorConst;
use app\api\consDir\OrderPrefixConst;
use app\api\services\CollectService;
use app\api\services\CouponService;
use app\api\services\MemberService;
use app\api\services\RabbitMqService;
use app\api\services\SandService;
use app\api\services\ShopService;
use app\api\services\SysService;
use app\common\libs\Jwt;
use app\common\libs\Singleton;
use app\common\models\Community\CommunityOrder;
use app\common\models\Community\CommunitySignUser;
use app\common\models\Member\Account;
use app\common\models\Member\Address;
use app\common\models\Member\Finance;
use app\common\models\Member\Member;
use app\common\models\Member\MemberAgency;
use app\common\models\Member\MemberAmountLog;
use app\common\models\Member\MemberCommunityAmountLog;
use app\common\models\Member\MemberDeductionAmountLog;
use app\common\models\Member\MemberDigitalMoneyLog;
use app\common\models\Member\MemberDigitalScoreLog;
use app\common\models\Member\MemberGxzLog;
use app\common\models\Member\MemberLogout;
use app\common\models\Member\MemberProfitLog;
use app\common\models\Member\MemberProfitPoolLog;
use app\common\models\Member\MemberRechargeMoneyList;
use app\common\models\Member\MemberRechargeOrder;
use app\common\models\Member\MemberSignInLog;
use app\common\models\Member\MemberWithdraw;
use app\common\models\Order\Order;
use app\common\models\Order\OrderPay;
use app\common\models\Packs\PacksOrder;
use app\common\models\Shop\Shop;
use app\common\utils\CommonUtil;
use app\common\utils\RedLock;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Log;

/**
 * 用户模块
 * Class MemberLogic
 * @package app\api\logic
 */
class MemberLogic extends BaseLogic
{
    use Singleton;

    private $Arr = [
        'all' => '全部',
        'pay' => '支付',
        'order_cancel' => '退款',
    ];

    private $scoreArr = [
        'all' => '全部',
        'buy' => '购物获得',
    ];

    private $earningsArr = [
        'all' => '全部',
        'day_dividend' => '每日分红',
    ];

    public function invitePoster()
    {
        $userData['inviteCode'] = MemberService::getInstance()->createCode($this->userinfo->id);
        $userData['imgUrl'] = [
            'https://files.jiubaibei.com/202205/08211433-71928114211976313.png',
            'https://files.jiubaibei.com/202205/08211442-18922501516975902.png',
            'https://files.jiubaibei.com/202205/08211451-38510801343001190.png',
        ];
        return $userData;
    }

    public function inviteShop(): array
    {
        $userData['inviteCode'] = MemberService::getInstance()->createCode($this->userinfo->id);
        $userData['imgUrl'] = 'https://files.jiubaibei.com/202205/08210358-25151574631488210.png';
        return $userData;
    }

    public function addWithdraw($code, $price): bool
    {
        if (!RedLock::getInstance()->lock('addWithdraw:' . $this->userinfo->id, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }
        if (!is_numeric($price) || $price < 0) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        //获取用户信息
        $userData = MemberService::getInstance()->getUserInfo($this->userinfo->id);
        if (empty($userData['phone'])) {
            CommonUtil::throwException(ErrorConst::PHONE_NOT_EXIST, ErrorConst::PHONE_NOT_EXIST_MSG);
        }

//        //判断验证码
        /*$getCode = MemberCache::getUserCode($userData['phone'], 'Withdraw');
        if (empty($getCode) || $getCode != $code) {
            CommonUtil::throwException(ErrorConst::CODE_ERROR, ErrorConst::CODE_ERROR_MSG);
        }*/

        $finance = MemberService::getInstance()->finance($this->userinfo->id);
        if ($finance['amount'] < $price) {
            CommonUtil::throwException(ErrorConst::NO_PRICE_ERROR, ErrorConst::NO_PRICE_ERROR_MSG);
        }

        return true;
    }

    /**
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function withdrawInfo(): array
    {
        $finance = MemberService::getInstance()->finance($this->userinfo->id);
        $data = [
            'user_id' => $this->userinfo->id,
        ];
        $account = MemberService::getInstance()->getAccountInfo($data);
        $userInfo = MemberService::getInstance()->getUserInfo($this->userinfo->id);

        return [
            'phone' => $userInfo['phone'],
            'amount' => $finance['amount'],
            'aliName' => empty($account['aliName']) ? '' : $account['aliName'],
            'aliAccount' => empty($account['aliAccount']) ? '' : $account['aliAccount'],
            'withdrawMsg' => SysService::getInstance()->article(11),
        ];
    }

    /**
     * @param $startAt
     * @param $endAt
     * @param $type
     * @param $page
     * @param $pageSize
     * @param string $logType
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function amountLogList($startAt, $endAt, $type, $page, $pageSize, string $logType = 'amount'): array
    {
        $endAt = $endAt . ' 23:59:59';
        $where = [
            ['user_id', '=', $this->userinfo->id],
        ];
        if ($type != 'all' && isset($this->Arr[$type])) {
            $where[] = ['log_type', '=', $type];
        }

        if (!empty($startAt) && !empty($endAt)) {
            $where[] = ['create_at', 'between', [$startAt, $endAt]];
        } else {
            $sevenDaysAgo = time() - 7 * 24 * 3600; // 计算7天前的时间戳
            $sevenDaysAgo = date('Y-m-d H:i:s', $sevenDaysAgo);
            $where[] = ['create_at', '>=', $sevenDaysAgo];
        }
        $finance = MemberService::getInstance()->finance($this->userinfo->id);
        $amount = $finance['amount'];
        $logList = MemberAmountLog::getInstance()
            ->where($where)
            ->field('id,create_at,amount,status,remark')
            ->order('id desc')
            ->limit(($page - 1) * $pageSize, $pageSize)
            ->select();

        $logList = empty($logList) ? [] : $logList->toArray();

        foreach ($logList as &$val) {
            $val['days'] = date('m-d', strtotime($val['createAt']));
        }
        $arr = [];
        foreach ($logList as $v) {
            $arr[$v['days']][] = $v;
        }

        $income = MemberService::getInstance()->getUserAmountSum($this->userinfo->id, 1, $logType, $startAt, $endAt);
        $expend = MemberService::getInstance()->getUserAmountSum($this->userinfo->id, 2, $logType, $startAt, $endAt);

        return ['rows' => $arr, 'amount' => $amount, 'dayAmount' => bcsub($income, $expend, 2), 'income' => $income, 'expend' => $expend];
    }

    /**
     * @param $addressId
     * @param $addressType
     * @return bool
     */
    public function defaultAddress($addressId, $addressType): bool
    {
        $where = [
            ['user_id', '=', $this->userinfo->id],
        ];
        Address::getInstance()->where($where)->update(['is_default' => 0]);

        $where = [
            ['user_id', '=', $this->userinfo->id],
            ['id', '=', $addressId],
        ];
        Address::getInstance()->where($where)->update(['is_default' => 1, 'address_type' => $addressType]);
        return true;
    }

    /**删除地址
     * @param $addressId
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function delAddress($addressId): bool
    {
        if (!RedLock::getInstance()->lock('editAddress_' . $this->userinfo->id, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }
        $addressInfo = MemberService::getInstance()->addressDetail($this->userinfo->id, $addressId);
        if (empty($addressInfo)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        $where = [
            ['id', '=', $addressId],
            ['user_id', '=', $this->userinfo->id],
        ];
        Address::getInstance()->where($where)->update(['deleted' => 1]);
        return true;
    }

    /**
     * 修改用户地址
     * @param $data
     * @param $addressId
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function editAddress($data, $addressId): bool
    {
        if (!RedLock::getInstance()->lock('editAddress_' . $this->userinfo->id, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }
        $addressInfo = MemberService::getInstance()->addressDetail($this->userinfo->id, $addressId);
        if (empty($addressInfo)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        $isDefault = $data['is_default'];
        $isDefault = ($isDefault == 1) ? 1 : 0;
        if ($isDefault == 1) {
            $where = [
                ['user_id', '=', $this->userinfo->id],
            ];
            Address::getInstance()->where($where)->update(['is_default' => 0]);
        }

        $where = [
            'id' => $addressId,
            'user_id' => $this->userinfo->id,
        ];
        Address::getInstance()->where($where)->update($data);
        return true;
    }

    /**
     * 添加地址
     * @param $data
     * @return bool
     */
    public function addAddress($data): bool
    {
        if (!RedLock::getInstance()->lock('addAddress_' . $this->userinfo->id, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }
        $data['user_id'] = $this->userinfo->id;
        $isDefault = $data['is_default'];

        $isDefault = ($isDefault == 1) ? 1 : 0;
        if ($isDefault == 1) {
            $where = [
                ['user_id', '=', $this->userinfo->id],
            ];
            Address::getInstance()->where($where)->update(['is_default' => 0]);
        }

        Address::getInstance()->insert($data);
        return true;
    }

    /**
     * @param $addressId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function addressDetail($addressId): array
    {

        $address = MemberService::getInstance()->addressDetail($this->userinfo->id, $addressId);
        if (empty($address)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        return $address;
    }

    /**
     * @param $page
     * @param $pageSize
     * @return array
     */
    public function addressList($page, $pageSize): array
    {
        $addressList = MemberService::getInstance()->addressList($this->userinfo->id, $page, $pageSize);
        return ['rows' => $addressList];
    }

    /**
     * 修改用户账号信息
     * @param $editKey
     * @param $editVal
     * @param $editValDouble
     * @param $code
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function editAccount($editKey, $editVal, $editValDouble, $code): bool
    {

        //锁
        if (!RedLock::getInstance()->lock('editAccount_' . $this->userinfo->id, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }
        //获取用户信息
        $userData = MemberService::getInstance()->getUserInfo($this->userinfo->id);
        if (empty($userData['phone'])) {
            CommonUtil::throwException(ErrorConst::PHONE_NOT_EXIST, ErrorConst::PHONE_NOT_EXIST_MSG);
        }

        //判断验证码
        if ($editKey == 'Phone') {
            //更换手机号
            $mobile = $editVal;
        } else {
            $mobile = $userData['phone'];
        }
        $getCode = MemberCache::getUserCode($mobile, 'Bind');
        if (empty($getCode) || $getCode != $code) {
            CommonUtil::throwException(ErrorConst::CODE_ERROR, ErrorConst::CODE_ERROR_MSG);
        }

        switch ($editKey) {
            case 'PayPwd':
                $data = [
                    'pay_pwd' => $editVal,
                ];
                MemberService::getInstance()->editAccountVal($this->userinfo->id, $data);
                break;
            case 'Phone':
                $data = [
                    'phone' => $editVal,
                ];
                $member = MemberService::getInstance()->getUserInfoByPhone($editVal);
                if ($member) {
                    CommonUtil::throwException(ErrorConst::PHONE_EXIST_ERROR, ErrorConst::PHONE_EXIST_ERROR_MSG);
                }
                MemberService::getInstance()->editVal($this->userinfo->id, $data);
                break;
            case 'Idc':
                //身份证号转大写
                $editValDouble = strtoupper($editValDouble);
                $result = $this->verifyName($editValDouble, $editVal);
                if (!empty($result) && $result['status'] == 0) {
                    CommonUtil::throwException(ErrorConst::PARAM_ERROR, $result['msg']);
                }
                $data = [
                    'real_name' => $editVal,
                    'idc' => $editValDouble,
                    'deleted' => 0,
                ];
                $aliInfo = MemberService::getInstance()->getAccountInfo($data);
                if(isset($aliInfo['isOpenIdc']) && $aliInfo['isOpenIdc'] == 1){
                    $conf = sysconf('platform_conf');
                    $conf = html_entity_decode($conf, ENT_QUOTES, 'UTF-8');
                    $conf = json_decode($conf, true);
                    $count = Account::getInstance()->where($data)->count();
                    if($count >= $conf['idc_bind_count']){
                        CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::IDC_ERROR_MSG);
                    }
                    $data['is_open_idc'] = 1;
                }else{
                    if (!empty($aliInfo)) {
                        CommonUtil::throwException(ErrorConst::IDC_ERROR, ErrorConst::IDC_ERROR_MSG);
                    }
                }
                $ret = MemberService::getInstance()->editAccountVal($this->userinfo->id, $data);
                if ($ret) {
                    $event["exchange"] = config('rabbitmq.info_queue');
                    RabbitMqService::send($event, ['type' => 'real_name', 'data' => ['id' => $this->userinfo->id]]);
                }
                break;
            case 'Ali':
                $data = [
                    'ali_name' => $editVal,
                    'ali_account' => $editValDouble,
                    'deleted' => 0,
                ];
                $aliInfo = MemberService::getInstance()->getAccountInfo($data);
                if (!empty($aliInfo)) {
                    CommonUtil::throwException(ErrorConst::ACCOUNT_ERROR, ErrorConst::ACCOUNT_ERROR_MSG);
                }
                //判断实名认证
                $info = MemberService::getInstance()->getAccountInfo(['user_id' => $this->userinfo->id]);
                if (empty($info['realName'])) {
                    CommonUtil::throwException(ErrorConst::REAL_NAME_ERROR, ErrorConst::REAL_NAME_ERROR_MSG);
                }
                if ($info['realName'] != $editVal) {
                    CommonUtil::throwException(ErrorConst::REAL_NAME_NO_ERROR, ErrorConst::REAL_NAME_NO_ERROR_MSG);
                }
                MemberService::getInstance()->editAccountVal($this->userinfo->id, $data);
                break;
            default:
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function unbindAli($code): bool
    {
        //锁
        if (!RedLock::getInstance()->lock('unbindAli_' . $this->userinfo->id, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }
        //获取用户信息
        $userData = MemberService::getInstance()->getUserInfo($this->userinfo->id);
        if (empty($userData['phone'])) {
            CommonUtil::throwException(ErrorConst::PHONE_NOT_EXIST, ErrorConst::PHONE_NOT_EXIST_MSG);
        }
        /*$getCode = MemberCache::getUserCode($userData['phone'], 'Bind');
        if (empty($getCode) || $getCode != $code) {
            CommonUtil::throwException(ErrorConst::CODE_ERROR, ErrorConst::CODE_ERROR_MSG);
        }*/
        $data = [
            'ali_account' => '',
            'ali_name' => '',
            'update_at' => date('Y-m-d H:i:s')
        ];
        Account::getInstance()->where('user_id',$this->userinfo->id)->update($data);
        return true;
    }

    /**
     * @param $editKey
     * @param $editVal
     * @return bool
     */
    public function editVal($editKey, $editVal): bool
    {
        //锁
        if (!RedLock::getInstance()->lock('editVal:' . $this->userinfo->id, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }
        switch ($editKey) {
            case 'avatar':
                $data['avatar'] = $editVal;
                MemberService::getInstance()->editVal($this->userinfo->id, $data);
                break;
            case 'nickname':
                $data['user_name'] = $editVal;
                MemberService::getInstance()->editVal($this->userinfo->id, $data);
                break;
            default:
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        MemberCache::getUserInfo($this->userinfo->id);
        return true;
    }

    /**
     * @return array
     */
    public function testLogin(): array
    {
        $data = [
            'username' => 'hahah',
            'id' => 1,
            'phone' => 18868898835,
            'openId' => 'oPPLSt93ww9pzKI_tYfn7LOsSLZk',
            'loginTime' => time(),
        ];
        return ['token' => Jwt::getToken($data)];
    }

    /**
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function userInfo(): array
    {
        //获取用户信息
        $userData = MemberService::getInstance()->getUserInfo($this->userinfo->id);
        if (empty($userData)) {
            CommonUtil::throwException(ErrorConst::NOT_LOGIN_ERROR, ErrorConst::NOT_LOGIN_ERROR_MSG);
        }
        $userData['isBindCity'] = $userData['provinceId'] > 0 ? 1 : 0;

        //获取店铺信息
        $shopData = ShopService::getInstance()->getShopInfo($this->userinfo->id);

        //获取用户财务信息
        $finance = MemberService::getInstance()->finance($this->userinfo->id);
        $allGreen = '0.0000';
        if ($finance) {
            $allGreen = bcadd($finance['communityAmount'] + $finance['inviteAmount'] + $finance['giftBagAmount'] + $finance['bonus'], 0, 4);
        }
        $finance['allGreen'] = $allGreen;
        //获取用户绑定信息
        $account = MemberService::getInstance()->account($this->userinfo->id);
        if (isset($account['isActiveSd']) && $account['isActiveSd'] == 0) {
            $ret = SandService::getInstance()->accountMemberQuery($this->userinfo->id);
            if (!empty($ret['userInfo']['faceStatus']) && $ret['userInfo']['faceStatus'] == '01') {
                Account::getInstance()->where('user_id', $this->userinfo->id)->update(['is_active_sd' => 1]);

            }
        }
        if ($userData['inviteCode']) {
            $invite = MemberService::getInstance()->getUserInfo($userData['inviteId']);
            if (!empty($invite)) {
                $member = Member::getInstance()->where('id', $invite['userId'])->find();
                $invite['inviteCode'] = $member['inviteCode'];
            }
        }
        //今日绿色积分
        $where = [
            ['status', '=', 1],
            ['user_id', '=', $this->userinfo->id],
            //['log_type', '<>', 'community_premium'],
            ['create_at', '>=', date('Y-m-d')],
        ];
        $dayAmount = MemberCommunityAmountLog::getInstance()->where($where)->sum('amount') ?: 0;

        //今日贡献值
        $where = [
            ['status', '=', 1],
            ['user_id', '=', $this->userinfo->id],
            ['create_at', '>=', date('Y-m-d')],
        ];
        $dayGxz = MemberGxzLog::getInstance()->where($where)->sum('amount') ?: 0;
        $finance['deductionTotal'] = bcadd($finance['deduction'],$finance['communityDeduction'],4);
        return [
            'inviteInfo' => $invite ?? [],
            'aliName' => empty($account['aliName']) ? '' : '*' . mb_substr($account['aliName'], 1),
            'aliAccount' => empty($account['aliAccount']) ? '' : substr_replace($account['aliAccount'], '****', 3, 4),
            'realName' => $account['realName'] ?? '',
            'idc' => empty($account['idc']) ? '' : substr_replace($account['idc'], '**************', 2, 14),
            'idcNo' => $account['idc'] ?? '',
            'isPayPwd' => empty($account['payPwd']) ? 0 : 1,
            'isActiveSd' => $account['isActiveSd'] ?? 0,
            'dayAmount' => bcadd($dayAmount, 0, 4), //今日绿色积分
            'dayGxz' => bcadd($dayGxz, 0, 4), //今日贡献值
            'coupon' => CouponService::getInstance()->getCouponInfoCount($this->userinfo->id),
            'collect' => CollectService::getInstance()->getUserCollectCount($this->userinfo->id),
            'finance' => $finance,
            'shopDate' => $shopData,
            'userInfo' => $userData,
        ];

    }

    public function withdrawList($type, $page, $pageSize): array
    {
        $where = [
            'user_id' => $this->userinfo->id,

        ];
        if ($type > 0) {
            $where['status'] = $type;
        }
        $list = MemberWithdraw::getInstance()
            ->where($where)
            ->field('status,amount,create_at,remark')
            ->order('id desc')
            ->limit(($page - 1) * $pageSize, $pageSize)
            ->select();
        $list = empty($list) ? [] : $list->toArray();

        $allWithdraw = MemberWithdraw::getInstance()
            ->where(['user_id' => $this->userinfo->id])
            ->sum('amount');

        $successWithdraw = MemberWithdraw::getInstance()
            ->where(['user_id' => $this->userinfo->id, 'status' => 1])
            ->sum('amount');

        return ['rows' => $list, 'allWithdraw' => $allWithdraw, 'successWithdraw' => $successWithdraw, 'inviteAmount' => 0];
    }

    public function memberAmountLogList($startAt, $endAt, $logType, $page, $pageSize): array
    {
        $where = [
            ['user_id', '=', $this->userinfo->id],
        ];

        if (!in_array($logType, ['add_all', 'reduce_all'])) {
            if (!empty($logType)) {
                $where[] = ['log_type', '=', $logType];
            }
        } else {
            if ($logType == 'add_all') {
                $where[] = ['status', '=', 1];
            } else {
                $where[] = ['status', '=', 2];
            }
        }

        if (!empty($startAt) && !empty($endAt)) {
            $endAt = $endAt . ' 23:59:59';
            $where[] = ['create_at', 'between', [$startAt, $endAt]];
        }
        $finance = MemberService::getInstance()->finance($this->userinfo->id);
        $amount = $finance['amount'];
        $logList = MemberAmountLog::getInstance()
            ->where($where)
            ->order('id desc')
            ->limit(($page - 1) * $pageSize, $pageSize)
            ->select();

        $logList = empty($logList) ? [] : $logList->toArray();

        foreach ($logList as &$val) {
            $val['days'] = date('m-d', strtotime($val['createAt']));
        }
        $arr = [];
        foreach ($logList as $v) {
            $arr[$v['days']][] = $v;
        }

        $income = MemberService::getInstance()->getAmountSum($this->userinfo->id, 1);
        $expend = MemberService::getInstance()->getAmountSum($this->userinfo->id, 2);
        $dayAmount = MemberService::getInstance()->getAmountSum($this->userinfo->id, 1, 1);
        $logType = MemberService::getInstance()->logType();
        return [
            'typeArr' => $logType,
            'rows' => $arr,
            'amount' => $amount, //当前
            'dayAmount' => $dayAmount, //今日
            'income' => $income, // 今日收益
            'expend' => $expend, //支出
            'frozen' => 0, //冻结
        ];
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function getAmountLog($startAt, $endAt, $logType, $page, $pageSize, $type): array
    {
        $where = [
            ['user_id', '=', $this->userinfo->id],
            ['type', '=', $type],
        ];
        if (!in_array($logType, ['add_all', 'reduce_all'])) {
            if (!empty($logType)) {
                if ($logType) {
                    if ($logType == 'area_co_earnings') {
                        //社区区域
                        $where[] = ['log_type', 'in', ['province_community_earnings', 'city_community_earnings', 'area_community_earnings']];
                    } elseif ($logType == 'area_me_earnings') {
                        //会员区域
                        $where[] = ['log_type', 'in', ['province_user_earnings', 'city_user_earnings', 'area_user_earnings','province_earnings', 'city_earnings', 'area_earnings']];
                    } elseif ($logType == 'area_shop_earnings') {
                        //区域（省/市/区县）商家让利收益
                        $where[] = ['log_type', 'in', ['shop_province_earnings', 'shop_city_earnings', 'shop_area_earnings']];
                    } elseif($logType == 'service_earnings'){
                        $where[] = ['log_type', 'in', ['spread_service_earnings','spread_ping_service_earnings']];
                    } elseif($logType == 'operate_activity_earnings'){
                        $where[] = ['log_type', 'in', ['operate_activity_earnings','activity_service_permanent_earnings','activity_direct_permanent_earnings']];
                    } else {
                        $where[] = ['log_type', '=', $logType];
                    }
                }
            }
        } else {
            if ($logType === 'add_all') {
                $where[] = ['status', '=', 1];
            } elseif ($logType === 'reduce_all') {
                $where[] = ['status', '=', 2];
            }
        }

        if (!empty($startAt) && !empty($endAt)) {
            $endAt = $endAt . ' 23:59:59';
            $where[] = ['create_at', 'between', [$startAt, $endAt]];
        } else {
            $sevenDaysAgo = time() - 7 * 24 * 3600; // 计算7天前的时间戳
            $sevenDaysAgo = date('Y-m-d H:i:s', $sevenDaysAgo);
            $where[] = ['create_at', '>=', $sevenDaysAgo];
        }

        $finance = MemberService::getInstance()->finance($this->userinfo->id);
        $typeData = [
            0 => 'communityAmount',
            1 => 'giftBagAmount',
            2 => 'inviteAmount',
            3 => 'bonus', // TODO 2024-05-25 字段名称带定义
        ];
        $amount = $finance[$typeData[$type]] ?? '0.0000';
        $logList = MemberCommunityAmountLog::getInstance()
            ->where($where)
            ->order('id desc')
            ->page($page, $pageSize)
            ->select();

        $logList = empty($logList) ? [] : $logList->toArray();

        foreach ($logList as &$val) {
            $val['days'] = date('m-d', strtotime($val['createAt']));
            if($val['type'] == 0 && in_array($val['logType'],['province_community_earnings', 'city_community_earnings', 'area_community_earnings'])){
                $val['logType'] = 'area_co_earnings';
            }
            if($val['type'] == 0 && in_array($val['logType'],['province_user_earnings', 'city_user_earnings', 'area_user_earnings'])){
                $val['logType'] = 'area_me_earnings';
            }
            if($val['type'] == 1 && in_array($val['logType'],['province_earnings', 'city_earnings', 'area_earnings'])){
                $val['logType'] = 'area_me_earnings';
            }
            if($val['type'] == 2 && in_array($val['logType'],['province_user_earnings', 'city_user_earnings', 'area_user_earnings'])){
                $val['logType'] = 'area_me_earnings';
            }
        }
        $arr = [];
        foreach ($logList as $v) {
            $arr[$v['days']][] = $v;
        }

        $income = MemberService::getInstance()->getAmountLogSum($this->userinfo->id, 1, 0, $type);
        $expend = MemberService::getInstance()->getAmountLogSum($this->userinfo->id, 2, 0, $type);
        $dayAmount = MemberService::getInstance()->getAmountLogSum($this->userinfo->id, 1, 1, $type);
        if ($type == 0) {
            $logTypeList = $this->logTypeData();
        } elseif ($type == 1) {
            $logTypeList = $this->logTypePacksData();
        } elseif ($type == 2) {
            $logTypeList = $this->logTypeSpreadData();
        } else {
            $logTypeList = $this->logTypeBonusData();
        }

        return [
            'typeArr' => $logTypeList,
            'rows' => $arr,
            'amount' => $amount, //当前
            'dayAmount' => bcadd($dayAmount, 0, 4), //今日
            'income' => bcadd($income, 0, 4), // 今日收益
            'expend' => bcadd($expend, 0, 4), //支出
            'frozen' => '0.0000', //冻结
        ];
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function getGxzLog($startAt, $endAt, $logType, $page, $pageSize): array
    {
        $where = [
            ['user_id', '=', $this->userinfo->id],
        ];
        if (!in_array($logType, ['add_all', 'reduce_all'])) {
            if (!empty($logType)) {
                $where[] = ['log_type', '=', $logType];
            }
        } else {
            if ($logType == 'add_all') {
                $where[] = ['status', '=', 1];
            } else {
                $where[] = ['status', '=', 2];
            }
        }

        if (!empty($startAt) && !empty($endAt)) {
            $endAt = $endAt . ' 23:59:59';
            $where[] = ['create_at', 'between', [$startAt, $endAt]];
        } else {
            $sevenDaysAgo = time() - 7 * 24 * 3600; // 计算7天前的时间戳
            $sevenDaysAgo = date('Y-m-d H:i:s', $sevenDaysAgo);
            $where[] = ['create_at', '>=', $sevenDaysAgo];
        }

        $finance = MemberService::getInstance()->finance($this->userinfo->id);
        $amount = $finance['gxz'];
        $logList = MemberGxzLog::getInstance()
            ->where($where)
            ->order('id desc')
            ->page($page, $pageSize)
            ->select();

        $logList = empty($logList) ? [] : $logList->toArray();

        foreach ($logList as &$val) {
            $val['days'] = date('m-d', strtotime($val['createAt']));
        }
        $arr = [];
        foreach ($logList as $v) {
            $arr[$v['days']][] = $v;
        }

        $income = MemberService::getInstance()->getGxzLogSum($this->userinfo->id, 1, 0);
        $expend = MemberService::getInstance()->getGxzLogSum($this->userinfo->id, 2, 0);
        $dayAmount = MemberService::getInstance()->getGxzLogSum($this->userinfo->id, 1, 1);
        $profit = MemberProfitLog::getInstance()->where('user_id', $this->userinfo->id)->sum('amount') ?: '0.00';

        return [
            'typeArr' => $this->logTypeGxgData(),
            'rows' => $arr,
            'amount' => $amount, //当前
            'dayAmount' => bcadd($dayAmount, 0, 4), //今日
            'income' => bcadd($income, 0, 4), // 今日收益
            'expend' => bcadd($expend, 0, 4), //支出
            'frozen' => 0, //冻结
            'profit' => $profit, //累计分红
        ];
    }

    public function logTypeGxgData(): array
    {
        return [
            [
                'name' => '收入',
                'list' => [
                    ['key' => 'add_all', 'name' => '全部'],
                    ['key' => 'community', 'name' => '社区竞拍'],
                    ['key' => 'community_op', 'name' => '支付服务费'],
                    ['key' => 'reg_user', 'name' => '新人注册'],
                    ['key' => 'invite_user', 'name' => '邀请会员'],
                    ['key' => 'invite_shop', 'name' => '邀请商家'],
                    ['key' => 'packs', 'name' => '购买礼包'],
                    ['key' => 'offline', 'name' => '线下订单消费'],
                    ['key' => 'online', 'name' => '线上订单消费'],
                    ['key' => 'real_name', 'name' => '实名认证赠送'],
                    ['key' => 'first_online', 'name' => '第一次线上订单消费'],
                    ['key' => 'first_offline', 'name' => '第一次线下订单消费'],
                    ['key' => 'sign_in', 'name' => '签到'],
                    ['key' => 'adv', 'name' => '看广告'],
                    ['key' => 'share', 'name' => '分享商品'],
                    ['key' => 'first_packs', 'name' => '第一次买礼包'],
                    ['key' => 'first_community', 'name' => '第一次竞拍社区'],
                    ['key' => 'lottery_add', 'name' => '抽奖赠送'],
                    ['key' => 'carefree', 'name' => '无忧消费订单'],
                    ['key' => 'card_buy', 'name' => '购买会员卡赠送'],
                    ['key' => 'service', 'name' => '生活馆订单消费'],
                    ['key' => 'back_inc', 'name' => '后台添加'],
                ],
            ],
            [
                'name' => '支出',
                'list' => [
                    ['key' => 'reduce_all', 'name' => '全部'],
                    ['key' => 'exchange_pay', 'name' => '贡献值兑换商品'],
                    ['key' => 'lottery_dec', 'name' => '抽奖扣除'],
                    ['key' => 'back_dec', 'name' => '后台扣除'],
                ],
            ],
        ];
    }

    /**
     * 社区类型
     * @return array[]
     */
    public function logTypeData(): array
    {
        return [
            [
                'name' => '收入',
                'list' => [
                    ['key' => 'add_all', 'name' => '全部'],
                    ['key' => 'community_premium', 'name' => '社区溢价收益'],
                    ['key' => 'vip_earnings', 'name' => 'vip直推收益'],
                    ['key' => 'service_earnings', 'name' => '服务商收益'],
                    ['key' => 'service_team_earnings', 'name' => '服务商团队收益'],
                    ['key' => 'business_earnings', 'name' => '事业部收益'],
                    ['key' => 'area_co_earnings', 'name' => '区域社区转让收益'],
                    ['key' => 'area_me_earnings', 'name' => '区域会员竞拍收益'],
                    ['key' => 'operate_activity_earnings', 'name' => '活动赠送'],
                    ['key' => 'recruit_partner_earnings', 'name' => '招募社区合伙人'],
                    ['key' => 'recruit_direct_earnings', 'name' => '招募直推收益'],
                    ['key' => 'back_inc', 'name' => '后台添加'],
                ],
            ],
            [
                'name' => '支出',
                'list' => [
                    ['key' => 'reduce_all', 'name' => '全部'],
                    ['key' => 'change', 'name' => '兑现到个人余额'],
                    ['key' => 'change_bag', 'name' => '兑现到个人电子钱包'],
                    ['key' => 'back_dec', 'name' => '后台扣除'],
                ],
            ],
        ];
    }

    /**
     * 礼包类型
     * @return array[]
     */
    public function logTypePacksData(): array
    {
        return [
            [
                'name' => '收入',
                'list' => [
                    ['key' => 'add_all', 'name' => '全部'],
                    ['key' => 'vip_earnings', 'name' => '直推收益'],
                    ['key' => 'service_earnings', 'name' => '服务商收益'],
                    ['key' => 'ping_service_earnings', 'name' => '平级服务商收益'],
                    ['key' => 'business_earnings', 'name' => '事业部收益'],
                    ['key' => 'community_op_earnings', 'name' => '社区经营者收益'],
                    ['key' => 'area_me_earnings', 'name' => '区域收益'],
                    ['key' => 'back_inc', 'name' => '后台添加'],
                ],
            ],
            [
                'name' => '支出',
                'list' => [
                    ['key' => 'reduce_all', 'name' => '全部'],
                    ['key' => 'change', 'name' => '兑现到个人余额'],
                    ['key' => 'back_dec', 'name' => '后台扣除'],
                ],
            ],
        ];
    }

    public function logTypeSpreadData(): array
    {
        return [
            [
                'name' => '收入',
                'list' => [
                    ['key' => 'add_all', 'name' => '全部'],
                    ['key' => 'direct_member_earnings', 'name' => '直推会员消费收益'],
                    ['key' => 'community_member_earnings', 'name' => '社区会员消费收益'],
                    ['key' => 'area_me_earnings', 'name' => '区域会员消费收益'],
                    ['key' => 'direct_shop_earnings', 'name' => '直推商家让利收益'],
                    ['key' => 'community_shop_earnings', 'name' => '社区商家让利收益'],
                    ['key' => 'area_shop_earnings', 'name' => '区域商家让利收益'],
                    ['key' => 'spread_service_earnings', 'name' => '服务商收益'],
                    ['key' => 'ping_service_earnings', 'name' => '平级服务商收益'],
                    ['key' => 'spread_partner_earnings', 'name' => '合伙人收益'],
                    ['key' => 'back_inc', 'name' => '后台添加'],
                ],
            ],
            [
                'name' => '支出',
                'list' => [
                    ['key' => 'reduce_all', 'name' => '全部'],
                    ['key' => 'change', 'name' => '兑现到个人余额'],
                    ['key' => 'back_dec', 'name' => '后台扣除'],
                ],
            ],
        ];
    }

    public function logTypeBonusData(): array
    {
        return [
            [
                'name' => '收入',
                'list' => [
                    ['key' => 'add_all', 'name' => '全部'],
                    ['key' => 'add', 'name' => '贡献值分红'],
                    ['key' => 'shareholder_earnings', 'name' => '股东分红'],
                    ['key' => 'back_inc', 'name' => '后台添加'],
                ],
            ],
            [
                'name' => '支出',
                'list' => [
                    ['key' => 'reduce_all', 'name' => '全部'],
                    ['key' => 'change', 'name' => '兑现到个人余额'],
                    ['key' => 'back_dec', 'name' => '后台扣除'],
                ],
            ],
        ];
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getAmountTypeList($isAgency = 0): array
    {
        $finance = MemberService::getInstance()->finance($this->userinfo->id);
        $all = bcadd(bcadd($finance['inviteAmount'], $finance['giftBagAmount'], 4), $finance['communityAmount'], 4);
        $all = bcadd($all, $finance['bonus'], 4);
        //$all = $finance['amount'];
        //社区
        $todayCommunity = MemberService::getInstance()->getAmountLogSum($this->userinfo->id, 1, 1, 0);
        //礼包
        $todayGiftBag = MemberService::getInstance()->getAmountLogSum($this->userinfo->id, 1, 1, 1);
        //推广
        $todayInvite = MemberService::getInstance()->getAmountLogSum($this->userinfo->id, 1, 1, 2);
        //分红
        $todayBonus = MemberService::getInstance()->getAmountLogSum($this->userinfo->id, 1, 1, 3);
        $data = [
            [
                'logo' => '',
                'name' => '社区绿色积分',
                'desc' => '数字社区相关收益，可兑换到余额',
                'amount' => $finance['communityAmount'],
                'todayAmount' => bcadd($todayCommunity, 0, 4),
                'type' => 0,
            ],
            [
                'logo' => '',
                'name' => '礼包绿色积分',
                'desc' => '推荐礼包相关收益，可兑换到余额',
                'amount' => $finance['giftBagAmount'],
                'todayAmount' => bcadd($todayGiftBag, 0, 4),
                'type' => 1,
            ],
            [
                'logo' => '',
                'name' => '推广绿色积分',
                'desc' => '推广会员消费、商家流水收益，可兑换到余额',
                'amount' => $finance['inviteAmount'],
                'todayAmount' => bcadd($todayInvite, 0, 4),
                'type' => 2,
            ],
            // TODO 2024-05-25 17:40:33 leeyi
            [
                'logo' => '',
                'name' => '分红绿色积分',
                'desc' => '对平台作出贡献的会员，获得的分润，可兑换到余额',
                'amount' => $finance['bonus'],
                'todayAmount' => bcadd($todayBonus, 0, 4),
                'type' => 3,
            ],
        ];

        $agencyData = [];
        if ($isAgency) {
            $where = [
                ['user_id', '=', $this->userinfo->id],
                ['status', '=', 1],
                ['deleted', '=', 0],
            ];
            $agency = MemberAgency::getInstance()->where($where)->find();
            $agencyData['level'] = $agency['provinceName'] . $agency['cityName'] . $agency['countryName'] . $agency['streetName'] . '合伙人';
            //1省 2市 3区代
            $where = [];
            if ($agency['isAgency'] == 1) {
                $where = [
                    ['province_id', '=', $agency['provinceId']]
                ];
            } elseif ($agency['isAgency'] == 2) {
                $where = [
                    ['city_id', '=', $agency['cityId']]
                ];
            } else {
                if ($agency['streetId']) {
                    $where = [
                        ['street_id', '=', $agency['streetId']]
                    ];
                } else {
                    $where = [
                        ['country_id', '=', $agency['countryId']]
                    ];
                }
            }
            //今日新入驻商家数
            $agencyData['shopCount'] = Shop::getInstance()->where($where)->count();
            //今日新注册会员数
            $agencyData['userCount'] = Member::getInstance()->where($where)->count();
            //当前余额
            $agencyData['amount'] = $finance['amount'];
        }
        return ['all' => $all, 'data' => $data, 'agencyData' => $agencyData];
    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function signUserList($status, $page, $pageSize): array
    {
        $where = [
            ['user_id', '=', $this->userinfo->id],
            ['sign_status', '=', $status]
        ];
        /*if ($status != 3) {
            $where[] = ['sign_status', '=', $status];
        } else {
            //过期
            $where[] = ['expire_at', '<', date('Y-m-d H:i:s')];
        }*/


        $data = CommunitySignUser::getInstance()->where($where)->page($page, $pageSize)->order('id desc')->select();
        foreach ($data as &$v) {
            if ($v['signStatus'] == 1 && $v['expireAt'] < date('Y-m-d H:i:s')) {
                //过期
                $v['signStatus'] = 3;
            }
            $v['typeName'] = '';
            if ($v['type'] == 1) {
                $v['typeName'] = '社区签到红包';
            }
        }
        $where = [
            ['sign_status', 'in', [1, 2]],
            ['expire_at', '>', date('Y-m-d H:i:s')],
        ];
        $amount = CommunitySignUser::getInstance()->where($where)->sum('amount');

        return ['redBag' => bcadd($amount, 0, 2), 'data' => $data];
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function getDigitalLog($startAt, $endAt, $logType, $page, $pageSize, $type): array
    {
        $where = [
            ['user_id', '=', $this->userinfo->id],
        ];

        if (!in_array($logType, ['add_all', 'reduce_all'])) {
            if (!empty($logType)) {
                $where[] = ['log_type', '=', $logType];
            }
        } else {
            if ($logType == 'add_all') {
                $where[] = ['status', '=', 1];
            } else {
                $where[] = ['status', '=', 2];
            }
        }

        if (!empty($startAt) && !empty($endAt)) {
            $endAt = $endAt . ' 23:59:59';
            $where[] = ['create_at', 'between', [$startAt, $endAt]];
        } else {
            $sevenDaysAgo = time() - 7 * 24 * 3600; // 计算7天前的时间戳
            $sevenDaysAgo = date('Y-m-d H:i:s', $sevenDaysAgo);
            $where[] = ['create_at', '>=', $sevenDaysAgo];
        }
        $finance = MemberService::getInstance()->finance($this->userinfo->id);
        $typeData = [
            1 => 'digitalMoney',
            2 => 'digitalScore',
        ];
        $amount = $finance[$typeData[$type]];
        if ($type == 1) {
            $db = MemberDigitalMoneyLog::getInstance();
            $logType = MemberService::getInstance()->logDigitalAssetType();
        } else {
            $db = MemberDigitalScoreLog::getInstance();
            $logType = MemberService::getInstance()->logDigitalScoreType();
        }
        $logList = $db
            ->where($where)
            ->order('id desc')
            ->page($page, $pageSize)
            ->select();

        foreach ($logList as &$val) {
            $val['days'] = date('m-d', strtotime($val['createAt']));
        }
        $arr = [];
        foreach ($logList as $v) {
            $arr[$v['days']][] = $v;
        }

        $income = MemberService::getInstance()->getAmountDigitalLogSum($this->userinfo->id, 1, 0, $type);
        $expend = MemberService::getInstance()->getAmountDigitalLogSum($this->userinfo->id, 2, 0, $type);
        $dayAmount = MemberService::getInstance()->getAmountDigitalLogSum($this->userinfo->id, 2, 1, $type);
        return [
            'typeArr' => $logType,
            'rows' => $arr,
            'amount' => $amount, //当前
            'dayAmount' => $dayAmount, //今日
            'income' => $income, // 今日收益
            'expend' => $expend, //支出
            'frozen' => 0, //冻结'
        ];
    }

    public function verifyName($idCard, $name): array
    {
        $host = "https://dfidveri.market.alicloudapi.com";
        $path = "/verify_id_name";
        $method = "POST";
        $appcode = config('verifyname.AppCode');
        $headers = [];
        $headers[] = "Authorization:APPCODE " . $appcode;
        //根据API的要求，定义相对应的Content-Type
        $headers[] = "Content-Type" . ":" . "application/x-www-form-urlencoded; charset=UTF-8";
        $querys = "";
        $bodys = "id_number=" . $idCard . "&name=" . $name;
        $url = $host . $path;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $output = curl_exec($curl);
        curl_close($curl);

        $str = substr($output, strpos($output, '{"'));
        $result = json_decode($str, true);
        if ($result && $result['status'] == 'OK') {
            if ($result['state'] == 1) {
                return ['status' => 1, 'msg' => '成功'];
            } elseif ($result['state'] == 2) {
                return ['status' => 0, 'msg' => '认证失败，身份证号码和姓名不匹配'];
            } else {
                return ['status' => 0, 'msg' => $result['result_message'] ?? ''];
            }
        } else {
            Log::error(json_encode($result,256));
            return ['status' => 0, 'msg' => '认证请求失败'];
        }
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getMemberRechargeMoneyList(): array
    {
        $where = [
            ['deleted', '=', 0],
            ['status', '=', 1],
        ];
        return MemberRechargeMoneyList::getInstance()->where($where)->order('sort desc')->select()->toArray();
    }

    public function rechargeCreateOrder($money): array
    {
        if (!RedLock::getInstance()->lock('recharge:' . $this->userinfo->id, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }
        if ($money <= 0) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }

        MemberRechargeOrder::getInstance()->startTrans();
        $orderNo = getNo(OrderPrefixConst::RC);
        $orderPayNo = getNo(OrderPrefixConst::RC . 'Pay');
        $order = [];
        try {
            $data = [
                'order_no' => $orderNo,
                'money' => $money,
                'user_id' => $this->userinfo->id,
                'expire_at' => date('Y-m-d H:i:s', strtotime('+5 minute')),
            ];
            MemberRechargeOrder::getInstance()->insert($data);
            //支付订单
            $data = [
                'user_id' => $this->userinfo->id,
                'pay_amount' => 0,
                'pay_price' => $money,
                'order_no' => $orderNo,
                'pay_no' => $orderPayNo,
                'pay_status' => 4,
                'expire_at' => date('Y-m-d H:i:s', strtotime('+15 minute')),
                'order_status' => 8,
            ];
            OrderPay::getInstance()->insert($data);
            $order = MemberRechargeOrder::getInstance()->where('order_no', $orderNo)->find()->toArray();
        } catch (\Exception $e) {
            MemberRechargeOrder::getInstance()->rollback();
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, $e->getMessage());
        }
        MemberRechargeOrder::getInstance()->commit();
        return ['order' => $order, 'sand' => SandLogic::getInstance()->orderCreateScan($money, $orderPayNo)];
    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function getTaskGxz($type): array
    {
        if (!RedLock::getInstance()->lock('task:gxz:' . $this->userinfo->id, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }
        if (!in_array($type, [1, 2])) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }

        if ($type == 1) {
            $data = Marketing::getKeyData('task', 'adv');
        } else {
            $data = Marketing::getKeyData('task', 'share');
        }
        if (empty($data)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        if ($data['status'] != 1) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        if ($data['count'] <= 0 || $data['gxz'] <= 0) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        $where = [];
        switch ($data['time_type']) {
            case 1:
                $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                $where[] = ['create_at', '>', date('Y-m-d', $beginToday)];
                break;
            case 2:
                //本周起始时间戳和结束时间戳
                $startTime = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1, date('y'));
                $endTime = mktime(23, 59, 59, date('m'), date('d') - date('w') + 7, date('y'));
                $where[] = ['create_at', 'between', [date('Y-m-d H:i:s', $startTime), date('Y-m-d H:i:s', $endTime)]];
                break;
            case 3:
                //本月起始时间戳和结束时间戳
                $beginThisMonth = mktime(0, 0, 0, date('m'), 1, date('Y'));
                $endThisMonth = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
                $where[] = ['create_at', 'between', [date('Y-m-d H:i:s', $beginThisMonth), date('Y-m-d H:i:s', $endThisMonth)]];
                break;
            case 4:
                //获取当前季度
                $season = ceil((date('m')) / 3);
                //本季度起始时间戳和结束时间戳
                $starTime = mktime(0, 0, 0, $season * 3 - 3 + 1, 1, date('Y'));
                $endTime = mktime(23, 59, 59, $season * 3, date('t', mktime(0, 0, 0, $season * 3, 1, date("Y"))), date('Y'));
                $where[] = ['create_at', 'between', [date('Y-m-d H:i:s', $starTime), date('Y-m-d H:i:s', $endTime)]];
                break;
            case 5:
                //当前年份
                $currentYear = date("Y");
                $startOfYear = $currentYear . '-01-01';
                $where[] = ['create_at', '>=', $startOfYear];
            default:
        }
        $where[] = ['user_id', '=', $this->userinfo->id];
        $where[] = ['status', '=', 1];
        //赠送贡献值
        if ($type == 1) {
            $msg = '看广告，赠送贡献值';
            $logType = 'adv';
            $where[] = ['log_type', '=', 'adv'];
        } else {
            $msg = '分享产品，赠送贡献值';
            $logType = 'share';
            $where[] = ['log_type', '=', 'share'];
        }
        $count = MemberGxzLog::getInstance()->where($where)->count();
        if ($count >= $data['count']) {
            //CommonUtil::throwException(ErrorConst::TASK_GET_GXZ_ERROR, ErrorConst::TASK_GET_GXZ_ERROR_MSG);
            return ['gxz' => 0];
        }
        MemberService::getInstance()->addFinanceLog($this->userinfo->id, $logType, $data['gxz'], 7, $msg);
        if($type == 1){
            MemberService::getInstance()->setActive($this->userinfo->id,3,1,3);
        }
        return ['gxz' => $data['gxz']];
    }

    /**
     * @throws DbException
     */
    public function getTaskInfo(): array
    {
        $adv = Marketing::getKeyData('task', 'adv');
        $share = Marketing::getKeyData('task', 'share');
        $new = Marketing::getKeyData('task', 'new');
        $user = Marketing::getKeyData('invite', 'user');
        $shop = Marketing::getKeyData('invite', 'shop');
        $signIn = Marketing::getKeyData('signin', 'signin_set');

        $where = [
            ['create_at', '>', date('Y-m-d')],
            ['user_id', '=', $this->userinfo->id],
            ['log_type', '=', 'adv'],
        ];
        $advCountEd = MemberGxzLog::getInstance()->where($where)->count();
        $where = [
            ['create_at', '>', date('Y-m-d')],
            ['user_id', '=', $this->userinfo->id],
            ['log_type', '=', 'share'],
        ];
        $shareCountEd = MemberGxzLog::getInstance()->where($where)->count();

        $userCountEd = Member::getInstance()->where(['invite_id' => $this->userinfo->id])->count();
        $shopCountEd = Member::getInstance()->where(['invite_id' => $this->userinfo->id, 'is_shop' => 1])->count();
        $yesterday = date('Y-m-d', strtotime('-1 day'));
        $where = [
            ['user_id', '=', $this->userinfo->id],
            ['create_at', '>=', $yesterday],
        ];
        $sign = MemberSignInLog::getInstance()->where($where)->order('id desc')->find();
        //今天是否签到
        $signed = 0;
        if (!empty($sign['createAt'])) {
            $signed = date('Y-m-d', strtotime($sign['createAt'])) == date('Y-m-d') ? 1 : 0;
        }

        $totalGxz = 0;
        $signDay = !empty($signIn['continue']) ? array_column($signIn['continue'], 'gxz_value', 'day') : [];
        for ($i = 1; $i <= $signIn['week']; $i++) {
            if (!empty($signDay[$i])) {
                $totalGxz = bcadd($totalGxz, $signDay[$i], 4);
            } else {
                $totalGxz = bcadd($totalGxz, $signIn['gxz_value'], 4);
            }
        }

        $count = $sign['successions'] ?? 0;
        $sign['successions'] = $sign['successions'] ?? 0;
        if ($signed == 0) {
            //判断昨天连续签到天数
            if ($sign['successions'] > 0 && $sign['successions'] % $signIn['week'] == 0) {
                $count = 0;
            }
        }

        $isRealNamed = Account::getInstance()->where('user_id', $this->userinfo->id)->value('real_name') ? 1 : 0;
        $where = [
            ['user_id', '=', $this->userinfo->id],
            ['status', '=', 2],
        ];
        $isFirstCommunity = CommunityOrder::getInstance()->where($where)->count() ? 1 : 0;
        $where = [
            ['member_id', '=', $this->userinfo->id],
            ['is_upgrade', '=', 1]
        ];
        $whereOr = [
            ['member_id', '=', $this->userinfo->id],
            ['status', '=', 3],
        ];
        $isFirstPacks = PacksOrder::getInstance()
            ->where($where)
            ->whereOr(function ($query) use ($whereOr) {
                $query->where($whereOr);
            })
            ->count() ? 1 : 0;

        $where = [
            ['user_id', '=', $this->userinfo->id],
            ['log_type', 'in', ['first_offline', 'first_online']]
        ];
        $isFirstOrder = MemberGxzLog::getInstance()->where($where)->count() ? 1 : 0;
        return [
            'signIn' => [
                'info' => $signIn,
                'count' => $count ?: 0,
                'signed' => $signed,
                'totalGxz' => $totalGxz,
            ],
            'day' => [
                'advGxz' => $adv['gxz'],
                'shareGxz' => $share['gxz'],
                'advCount' => $adv['count'],
                'advCountEd' => min($advCountEd, $adv['count']),
                'shareCount' => $share['count'],
                'shareCountEd' => min($shareCountEd, $share['count']),
            ],
            'spread' => [
                'userGxz' => $user['gxz_value'],
                'shopGxz' => $shop['gxz_value'],
                'userCount' => $user['limit'],
                'userCountEd' => min($userCountEd, $user['limit']),
                'shopCount' => $shop['limit'],
                'shopCountEd' => min($shopCountEd, $shop['limit']),
            ],
            'newPerson' => [
                'realName' => $new['real_name'],
                'isRealName' => $isRealNamed,
                'firstCommunity' => $new['first_community'],
                'isFirstCommunity' => $isFirstCommunity,
                'firstPacks' => $new['first_packs'],
                'isFirstPacks' => $isFirstPacks,
                'firstOrder' => $new['first_online'],
                'isFirstOrder' => $isFirstOrder,
                //'firstOnline' => $new['first_online'],
                //'firstOffline' => $new['first_offline'],
            ],
        ];
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function signIn(): array
    {
        if (!RedLock::getInstance()->lock('task:sign:in' . $this->userinfo->id, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }
        $signIn = Marketing::getKeyData('signin', 'signin_set');
        if ($signIn['status'] != 1) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        $signInData = MemberSignInLog::getInstance()->where('user_id', $this->userinfo->id)->whereTime('create_at', 'today')->find();
        if ($signInData) {
            CommonUtil::throwException(ErrorConst::TASK_SIGN_IN_ERROR, ErrorConst::TASK_SIGN_IN_ERROR_MSG);
        }
        $lastData = MemberSignInLog::getInstance()->where('user_id', $this->userinfo->id)->order('create_at', 'desc')->find();
        $yesterday = date('Y-m-d', strtotime('-1 day'));
        $successions = $lastData && $lastData['createAt'] > $yesterday ? $lastData['successions'] : 0;
        $successions++;

        //连续签到次数
        $successions = $successions % 7;
        if ($successions == 0) {
            $successions = 7;
        }

        $gxz = $signIn['gxz_value'];
        if ($successions > 1) {
            if (!empty($signIn['continue'])) {
                foreach ($signIn['continue'] as $v) {
                    if ($v['day'] == $successions) {
                        $gxz = $v['gxz_value'];
                        break;
                    }
                }
            }
        }

        //活跃值
        $activeData = Marketing::getKeyData('active', 'active_set');
        $activitySuccessions = $lastData && $lastData['createAt'] > $yesterday ? $lastData['activity_successions'] : 0;
        $activitySuccessions++;
        $week = 0;
        if(!empty($activeData)){
            if(!empty($activeData['sign_data'])) {
                foreach ($activeData['sign_data'] as $v) {
                    if($v['is_yes'] == 1 && $v['num'] > 0){
                        $week = $v['num'];
                        break;
                    }
                }
            }
        }

        $activitySuccessions = $activitySuccessions % $week;
        if ($activitySuccessions == 0) {
            $activitySuccessions = $week;
        }

        $data = [
            'user_id' => $this->userinfo->id,
            'successions' => $successions,
            'activity_successions' => $activitySuccessions,
        ];
        $id = MemberSignInLog::getInstance()->insertGetId($data);
        $event["exchange"] = config('rabbitmq.info_queue');
        RabbitMqService::send($event, ['type' => 'sign_in', 'data' => ['id' => $id]]);
        return ['gxz' => $gxz];
    }

    /**
     * @throws DbException
     */
    public function bonusTime(): array
    {
        $data = Marketing::getKeyData('profit', 'set');
        if (empty($data)) {
            return ['status' => 0, 'time' => 0];
        }
        if ($data['time_type'] == 1) {
            $getTime = date('Y-m-d', strtotime('+1 day'));
            $getTime = strtotime($getTime);
        } elseif ($data['time_type'] == 2) {
            $day = [
                1 => 'monday',
                2 => 'tuesday',
                3 => 'wednesday',
                4 => 'thursday',
                5 => 'friday',
                6 => 'saturday',
                7 => 'sunday',
            ];
            $weekDay = $day[$data['week']];
            if (date('w') > $data['week']) {
                //下周
                $getTime = strtotime("next $weekDay");
            } else {
                //这周
                $getTime = strtotime("this $weekDay");
            }
        } else {
            // 设置当月第几天，例如第10天
            $dayOfMonth = $data['month'];
            // 获取当前年份和月份
            $year = date('Y');
            $month = date('n');

            if (date('j') > $data['month']) {
                //创建下月第$dayOfMonth天的时间戳
                $getTime = mktime(0, 0, 0, $month + 1, $dayOfMonth, $year);
            } else {
                // 创建当月第$dayOfMonth天的时间戳
                $getTime = mktime(0, 0, 0, $month, $dayOfMonth, $year);
            }
        }
        //倒计时
        $time = strtotime('+3 hours', $getTime);
        $currentTimeStamp = time();
        $difference = $time - $currentTimeStamp;
        $day = floor($difference / (60 * 60 * 24));

        if($data['profit_type'] == 1){
            $canBonus = $this->canBonus($data);
        }else{
            $canBonus = MemberService::getInstance()->isLevelProfit($data,$this->userinfo->id);
        }

        $where = [
            ['user_id','=',$this->userinfo->id],
            ['deleted','=',0],
            ['create_at','>=',date('Y-m-d 00:00:00')]
        ];
        $count = MemberProfitLog::getInstance()->where($where)->count();
        if($canBonus && $count < 1){
            $canBonus = 1;
        }else{
            $canBonus = 0;
        }

        //1购买指定商品 2购买指定专区
        $activity = Finance::getInstance()->where('user_id',$this->userinfo->id)->value('activity');
        //profit_type 1按贡献值加权分 2按会员等级分
        if($data['profit_type'] == 1){
            $is_low = 0;
        }else{
            if(isset($data['is_active'])){
                if(!empty($activity) && $activity >= 60){
                    $is_low = 0;
                }else{
                    $is_low = 1;
                }
            }else{
                $is_low = 0;
            }
        }

        return [
            'status' => (int)$data['status'],
            'time' => date('Y-m-d H:i:s', $time),
            'day' => $day,
            'canBonus' => $canBonus,
            'profitType' => $data['profit_type'],
            'is_low' => $is_low,
            'get_type' => $data['get_type'],
            'buy_type' => $data['buy_type'] ?? 0,
            'buy_product_id' => $data['buy_product_id'] ?? 0,
            'buy_special_id' => $data['buy_special_id'] ?? 0,
        ];
    }


    /**
     * 指定用户分红弹窗
     * @throws DbException
     */
    public function canBonus($data): int
    {
        //手工领取
        if($data['get_type'] == 2){
            //1每天 2每周 3每月
            if ($data['time_type'] == 2 && date('w') != $data['week']) {
                return 0;
            }

            if ($data['time_type'] == 3 && date('j') != $data['month']) {
                return 0;
            }
        }

        $whereOr = [];
        //会员贡献值
        if ($data['type'] == 0) {
            $where = [
                ['f.gxz', '>=', $data['gxz']],
                ['m.deleted', '=', 0]
            ];
        } else {
            //会员等级
            if (in_array(0, $data['level'])) {
                //全部会员贡献员
                $where = [
                    ['m.deleted', '=', 0]
                ];
            } else {
                //等级贡献值
                //服务商
                $where = [];
                if(in_array(2, $data['level'])){
                    $where = [
                        ['m.deleted', '=', 0],
                        ['m.is_partner', '=', 1]
                    ];
                }
                //代理
                if (in_array(3, $data['level'])) {
                    $whereOr = [
                        ['m.deleted', '=', 0],
                        ['m.is_agency', '>', 0],
                        ['m.id', '=', $this->userinfo->id]
                    ];
                }

            }
        }
        $ret = Member::getInstance()->alias('m')
            ->leftJoin('member_finance f', 'm.id=f.user_id')
            ->where('m.id', $this->userinfo->id)
            ->where($where)
            ->whereOr(function ($query) use ($whereOr) {
                $query->where($whereOr);
            })
            ->field('f.gxz,m.id')
            ->count();

        return !empty($ret) ? 1 : 0;
    }


    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function getProfit(): array
    {
        $data = Marketing::getKeyData('profit', 'set');
        if (empty($data)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        //禁用
        if ($data['status'] != 1) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '分红未开启');
        }
        //1每天 2每周 3每月
        if ($data['time_type'] == 2 && date('w') != $data['week']) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '未到分红时间');
        }

        if ($data['time_type'] == 3 && date('j') != $data['month']) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '未到分红时间');
        }
        if($data['profit_type'] == 1){
            //按贡献值加权分
            $profit = MemberService::getInstance()->getGxzProfit($data,$this->userinfo->id);
        }else{
            //按会员等级分
            $profit = MemberService::getInstance()->getLevelProfit($data,$this->userinfo->id);
        }
        if($profit === false){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '未到满足分红条件');
        }
        return ['profit' => $profit];
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function deductionLog($startAt, $endAt, $logType, $page, $pageSize): array
    {
        $where = [
            ['user_id', '=', $this->userinfo->id],
        ];

        if ($logType === 'add_all') {
            $where[] = ['status', '=', 1];
        } elseif ($logType === 'reduce_all') {
            $where[] = ['status', '=', 2];
        }

        if (!empty($startAt) && !empty($endAt)) {
            $endAt = $endAt . ' 23:59:59';
            $where[] = ['create_at', 'between', [$startAt, $endAt]];
        } else {
            $sevenDaysAgo = time() - 7 * 24 * 3600; // 计算7天前的时间戳
            $sevenDaysAgo = date('Y-m-d H:i:s', $sevenDaysAgo);
            $where[] = ['create_at', '>=', $sevenDaysAgo];
        }

        $finance = MemberService::getInstance()->finance($this->userinfo->id);
        $logList = MemberDeductionAmountLog::getInstance()
            ->where($where)
            ->order('id desc')
            ->page($page, $pageSize)
            ->select();

        $logList = empty($logList) ? [] : $logList->toArray();

        foreach ($logList as &$val) {
            $val['days'] = date('m-d', strtotime($val['createAt']));
        }

        $logTypeArr = [
            'change' => '抵扣券使用',
            'add' => '增加抵扣券',
            'buy' => '消费订单抵扣',
            'card_add' => '购买会员卡',
            'change_add' => '绿色积分兑换',
            'community_change' => '社区兑换',
            'back_inc' => '后台添加',
            'back_dec' => '后台扣除',
        ];
        $arr = [];
        foreach ($logList as $v) {
            $v['name'] = $logTypeArr[$v['logType']] ?? '';
            $arr[$v['days']][] = $v;
        }

        $where = [
            ['user_id','=',$this->userinfo->id],
            ['status','=',1],
            ['create_at','>=',date('Y-m-d')],
        ];
        $dayAmount = MemberDeductionAmountLog::getInstance()
            ->where($where)
            ->where('type','=',0)
            ->sum('amount') ?: '0.00';

        $communityDayAmount = MemberDeductionAmountLog::getInstance()
            ->where($where)
            ->where('type','=',1)
            ->sum('amount') ?: '0.00';

        $logTypeList =  [
            ['key' => '', 'name' => '全部'],
            ['key' => 'add_all', 'name' => '收入'],
            ['key' => 'reduce_all', 'name' => '支出'],
        ];
        return [
            'typeArr' => $logTypeList,
            'rows' => $arr,
            'amount' => $finance['deduction'] ?? '0.0000', //当前
            'communityAmount' => $finance['communityDeduction'] ?? '0.0000', //当前
            'dayAmount' => bcadd($dayAmount, 0, 4), //今日
            'communityDayAmount' => bcadd($communityDayAmount, 0, 4), //今日
            'income' => $finance['allDeduction'] ?? '0.0000', // 总抵扣金
            'expend' => bcsub($finance['allDeduction'],$finance['deduction'],4), //已使用抵扣金
        ];
    }

    public function userDisabled(): bool
    {
        Member::getInstance()->startTrans();
        try{
            Member::getInstance()->where('id',$this->userinfo->id)->update(['is_logout' => 1]);
            $data = [
                'phone' => $this->userinfo->phone,
                'user_id' => $this->userinfo->id,
            ];
            MemberLogout::getInstance()->insert($data);
        }catch (\Exception $e){
            Member::getInstance()->rollback();
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, $e->getMessage());
        }
        Member::getInstance()->commit();
        return true;
    }

}
